<template>
  <a-modal
    v-model:visible="visible"
    modal-class="metric-setting-modal"
    title-align="start"
    @close="closeModal"
    @before-open="beforeOpen"
    width="836px"
  >
    <template #title>
      <span class="title-text">{{ props.data.metricsName }}</span>
    </template>
    <a-form ref="formRef" :model="model" @submit.prevent auto-label-width>
      <a-form-item
        label="统计周期"
        required
        class="period-from-item"
        show-colon
      >
        <a-form-item
          field="statisticalPeriod.type"
          validate-trigger="change"
          :rules="[{ required: true, message: '请选择统计周期' }]"
          hide-label
          hide-asterisk
        >
          <a-select
            v-model="model.statisticalPeriod.type"
            :options="getStatisticalPeriodOption(timeframe!,statisticalPeriodOption)"
          >
            <template #arrow-icon>
              <IconCaretDown size="12" />
            </template>
          </a-select>
        </a-form-item>
        <template v-if="model.statisticalPeriod.type === 'recent'">
          <a-form-item
            field="statisticalPeriod.offset"
            validate-trigger="change"
            :rules="[{ required: true, message: '请填写统计周期' }]"
            hide-label
            hide-asterisk
          >
            <a-input-number
              v-model="model.statisticalPeriod.offset"
              placeholder="请输入"
              :min="1"
              :precision="0"
            />
          </a-form-item>
          <a-form-item
            field="statisticalPeriod.timeUnit"
            validate-trigger="change"
            :rules="[{ required: true, message: '请选择统计周期单位' }]"
            hide-label
            hide-asterisk
          >
            <a-select
              v-model="model.statisticalPeriod.timeUnit"
              :options="getStatisticalPeriodOption(timeframe!,statisticalPeriodUnitOption)"
            />
          </a-form-item>
        </template>
      </a-form-item>
      <a-form-item
        label="数值格式"
        field="numberFormat"
        :rules="[{ required: true, message: '请选择数值格式' }]"
        :validate-trigger="['change']"
        show-colon
      >
        <a-radio-group
          v-model="model.numberFormat"
          :options="numFormatOption"
        />
      </a-form-item>
      <a-form-item label="过滤条件" required show-colon>
        <FilterConfig
          v-if="visible"
          v-model="model.metricsConditions"
          v-model:rela="model.rela"
          :metricsId="props.data.metricsId"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="visible = false"> 取消 </a-button>
      <a-button @click="handleOk" type="primary"> 确定 </a-button>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
import { ref, watch, watchEffect, inject, Ref } from 'vue';
import FilterConfig from './filterConfig.vue';
import {
  statisticalPeriodOption,
  statisticalPeriodUnitOption,
  numFormatOption
} from '../../type';
import { cloneDeep } from 'lodash';
import { Message } from '@arco-design/web-vue';
import { getStatisticalPeriodOption } from '../../hooks';
import { IconCaretDown } from '@arco-design/web-vue/es/icon';

const props = withDefaults(
  defineProps<{
    modelValue: boolean;
    data: any;
  }>(),
  {
    modelValue: false,
    data: undefined
  }
);
const emits = defineEmits(['update:modelValue', 'update:data']);

const timeframe = inject<Ref>('min-timeframe');
const updateCurrentTimeframe = inject<(val: string) => void>(
  'update-current-timeframe'
);
const updateTimeframe = inject<(val: string) => void>('update-min-timeframe');

const visible = ref(false);
const formRef = ref();

const model = ref({
  metricsId: null,
  metricsName: '',
  statisticalPeriod: {
    offset: 1,
    timeUnit: 'day',
    type: 'BEFORE'
  },
  numberFormat: 'GE',
  rela: 'AND',
  metricsConditions: []
});
watchEffect(() => {
  if (props.data.metricsId) {
    model.value = cloneDeep(props.data);
  }
});

// 指标切换触发最小时间粒度变化,则更新默认统计周期,并更新v-model
watch(
  () => model.value.metricsId,
  () => {
    model.value.statisticalPeriod.type = timeframe!.value;
    let data = cloneDeep(model.value);
    emits('update:data', data);
  }
);

// 点击确定，更新指标时间粒度
const handleOk = async () => {
  const validateRes = await formRef.value.validate();
  if (validateRes) {
    return false;
  }
  if (
    model.value.metricsConditions.some(
      (item: any) => !item.dimId || !item.opType || !item.values.length
    )
  ) {
    Message.warning('请选择过滤条件');
    return false;
  }
  updateTimeUnit();
  let data = cloneDeep(model.value);
  data.metricsConditions.forEach((item: any) => {
    delete item._dimensionEnumOptions;
  });
  emits('update:data', data);
  visible.value = false;
};

const updateTimeUnit = () => {
  let timeUnit = '';
  let type = model.value.statisticalPeriod.type;
  if (type === 'recent') {
    timeUnit = model.value.statisticalPeriod.timeUnit;
  } else if (type.includes('_to_')) {
    timeUnit = 'day';
  } else {
    timeUnit = type;
  }
  model.value.statisticalPeriod.timeUnit = timeUnit;
  updateCurrentTimeframe!(timeUnit);
};

// 打开弹窗，重新赋值（点击确定有效）
const beforeOpen = () => {
  if (props.data.metricsId) {
    model.value = cloneDeep(props.data);
  }
};
// 关闭弹窗
const closeModal = () => {
  emits('update:modelValue', false);
};
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
  }
);
</script>
<style lang="scss">
.metric-setting-modal {
  .title-text {
    color: var(--color-text-1);
    font-weight: 600;
    font-size: 16px;
  }

  .period-from-item {
    margin-bottom: 0;
    .arco-form-item-content {
      flex: 0 0 auto;
      & > .arco-select,
      & > .arco-input-number {
        width: 120px;
        margin-right: 6px;
      }
    }
  }

  .row-remark {
    margin-bottom: 0;

    .arco-textarea-wrapper {
      width: 360px;
    }
  }
}
</style>
